const chalk = require('chalk')
const Koa = require('koa')
const router = require('@koa/router')()


const app = new Koa()

app.use(async (ctx, next) => {
  console.log(chalk.yellow('\nRequest: ----------------'))
  const req = ctx.request
  console.log(req.method, `[host: ${req.headers.host}]`, req.url)
  // console.log(req.method, req.URL.toString())  // 完整请求路径
  // Object.keys(req.headers).forEach(name => {   // 完整Header
  //   console.log(`  ${name}: ${req.headers[name]}`)
  // })

  ctx.body = '{"n": "Hello World"}'

  await next()
})

router.get('/test/newpath/:name', async (ctx, next) => {
  ctx.response.body = `{"/test/newpath": "${ctx.params.name}"}`
})

router.get('/api/:name', async (ctx, next) => {
  ctx.response.body = `{"API": "${ctx.params.name}"}`
})

router.post('/api/:name', async (ctx, next) => {
  ctx.response.body = `{"API": "${ctx.params.name}", "method": "POST"}`
})

router.get('/', async (ctx, next) => {
  ctx.response.body = '{"API": "/"}';
});

app.use(router.routes())

app.listen(5000)
console.log(`Server running at ${chalk.yellow('http://127.0.0.1:5000')}\n`)
